<template>
  <el-button type="primary" @click="dialogVisible=true">添加</el-button>

  <!--添加标签弹出框-->
  <el-dialog
      v-model="dialogVisible"
      :title="isAdd?'添加':'修改'"
      width="30%"
      :before-close="handleClose">
    <el-form ref="formRef"
             :model="aphorismFrom"
             :rules="rules"
             label-width="80px">
      <el-form-item label="作者姓名" prop="author">
        <el-input v-model="aphorismFrom.author" type="text" maxlength="20"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="名言警句" prop="content">
        <el-input v-model="aphorismFrom.content" type="textarea" :autofocus="true" :autosize="{ minRows: 3, maxRows: 5 }"
                  @keydown.enter="aphorismOperation" maxlength="70" show-word-limit/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="aphorismOperation">
          保存
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>

  <el-divider direction="vertical"></el-divider>
  <el-input
      v-model="searchText"
      placeholder="搜索标签"
      size="default"
      style="width: 350px"
      clearable
      maxlength="12"
      show-word-limit
      @clear="getAll"
      @keydown.enter="getAll"
  >
    <template #append>
      <el-button @click="getAll">
        <el-icon>
          <Search/>
        </el-icon>
      </el-button>
    </template>
  </el-input>
  <el-divider direction="vertical"></el-divider>
  <el-button :icon="Refresh" :loading="loading" @click="refreshTable">
    <span>刷新</span>
  </el-button>
  <el-divider direction="vertical"></el-divider>
  <el-button :loading="loading" type="danger" :disabled="DeleteManyDisable" @click="deleteMany">
    <span>批量删除</span>
  </el-button>
  <el-divider></el-divider>
  <!--展示区域-->
  <el-table :data="tableData" @selection-change="handleSelectionChange" stripe style="width: 100%">
    <el-table-column type="selection" width="55"/>
    <el-table-column prop="id" label="Id" width="80"/>
    <el-table-column prop="content" label="Content" min-width="220"/>
    <el-table-column prop="author" label="Author" width="220"/>
    <el-table-column fixed="right" label="操作" width="120">
      <template #default="scope">
        <el-link type="danger" @click="deleteAphorism(scope.row.id)">
          <el-icon>
            <Delete/>
          </el-icon>
        </el-link>
        <el-divider direction="vertical"></el-divider>
        <el-link type="primary" @click="editAphorism(scope.row)">
          <el-icon>
            <Edit/>
          </el-icon>
        </el-link>
      </template>
    </el-table-column>
  </el-table>

  <el-divider></el-divider>
  <!--分页-->
  <div style="display: flex;">
    <el-pagination
        v-model:current-page="current"
        v-model:page-size="size"
        :page-sizes="[15, 30, 45, 60]"
        :small="true"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin: auto;"
    />
  </div>
</template>

<script>
import {Search, Refresh} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";

export default {
  name: "Aphorism",
  data() {
    return {
      Refresh, Search,
      loading: false,
      searchText: "",
      dialogVisible: false,
      // false 表示修改标签
      isAdd: true,
      aphorismFrom: {
        id: null,
        content: "",
        author: "",
      },
      rules: {
        content: [
          {required: true, message: '请输入标签名', trigger: 'blur'},
          {min: 1, max: 70, message: '句子长度应该在1-70', trigger: 'blur'},
        ],
        author: [
          {min: 1, max: 20, message: '作者名长度应该在1-20', trigger: 'blur'},
        ],
      },
      tableData: [],
      total: 0,
      current: 1,
      size: 15,
      DeleteManyDisable: true,
      multipleSelection: []
    }
  },
  created() {
    this.getAll()
  },
  methods: {
    async getAll() {
      let {data: result} = await this.$http.get("/api/aphorism/getAphorisms", {
        params: {
          pageSize: this.size,
          pageNum: this.current,
          searchText: this.searchText
        }
      })
      this.tableData = result.dataMap.page.records
      this.current = result.dataMap.page.current
      this.total = result.dataMap.page.total
      this.size = result.dataMap.page.size
    },
    refreshTable() {
      this.loading = true
      this.getAll()
      this.loading = false
    },
    handleClose() {
      this.$refs.formRef.resetFields()
      this.dialogVisible = false
      this.aphorismFrom = {
        id: null,
        content: "",
        author: "",
      }
      this.isAdd = true
    },
    aphorismOperation() {
      if (this.isAdd) {
        this.addAphorism()
      } else {
        this.updateAphorism(this.aphorismFrom)
      }
    },
    editAphorism(item) {
      console.log(item)
      // es6 新特性，深拷贝
      this.aphorismFrom = {...item}
      this.isAdd = false
      this.dialogVisible = true
    },
    addAphorism() {
      this.$refs.formRef.validate(async (validate) => {
        if (validate) {
          let {data: result} = await this.$http.post("/api/aphorism/save", this.aphorismFrom)
          if (result.code === 400) {
            ElMessage.error({
              showClose: true, message: result.msg
            })
          } else {
            ElMessage.success({
              showClose: true, message: result.msg
            })
            this.handleClose()
            this.refreshTable()
          }
        } else {
          ElMessage.error({
            showClose: true, message: "表单填写有误！"
          })
        }
      })
    },
    async updateAphorism(item) {
      this.loading = true
      let {data: result} = await this.$http.post("/api/aphorism/updateAphorism", item)
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.loading = false
      this.handleClose()
      this.refreshTable()

    },
    async deleteAphorism(id) {
      this.loading = true
      let {data: result} = await this.$http.get("/api/aphorism/deleteAphorism", {
        params: {
          id: id,
        }
      })
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.refreshTable()
    },
    async deleteMany() {
      this.loading = true
      let {data: result} = await this.$http.post("/api/aphorism/deleteMany", this.multipleSelection.value)
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.refreshTable()
    },

    // 多选状态改变
    handleSelectionChange(val) {
      if (val.length === 0) {
        // 批量删除不可用
        this.DeleteManyDisable = true
      } else {
        this.DeleteManyDisable = false
      }
      let list = []
      val.forEach((item) => {
        list.push(item.id)
      })
      this.multipleSelection.value = list
    },

    // 分页大小改变
    handleSizeChange() {
      this.refreshTable()
    },
    // 分页页数改变
    handleCurrentChange() {
      this.refreshTable()
    },
  }
}
</script>

<style scoped>

</style>